package cn.zhj.base.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView

abstract class CommonAdapter <T> : RecyclerView.Adapter<CommonViewHolder>{
    protected var mContext: Context
    protected var mLayoutId = 0
    protected var mDatas: ArrayList<T>
    protected var mInflater: LayoutInflater? = null

    constructor(context: Context , layoutId:Int , datas:ArrayList<T>){
        mContext = context
        mLayoutId = layoutId
        mDatas = datas
        mInflater = LayoutInflater.from(context)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CommonViewHolder {
        var viewHolder: CommonViewHolder = CommonViewHolder.get(mContext , parent , mLayoutId)
        return viewHolder
    }

    override fun onBindViewHolder(holder: CommonViewHolder, position: Int) {
        convert(holder , mDatas.get(position) , position)
    }

    abstract fun convert(holder: CommonViewHolder, t: T, position: Int)

    override fun getItemCount(): Int {
        return mDatas.size
    }

    open fun appendListData(mDatas: ArrayList<T>?) {
        if (mDatas != null && mDatas.isNotEmpty()) {
            this.mDatas.addAll(mDatas)
        }
        notifyDataSetChanged()
    }

    open fun setListData(mDatas: ArrayList<T>?) {
        if (mDatas != null && mDatas.size > 0) {
            this.mDatas = mDatas
        }
        notifyDataSetChanged()
    }

    open fun removeItem(position: Int) {
        mDatas.removeAt(position)
        notifyItemRemoved(position)
        if (position != mDatas.size && mDatas.size != 0) {
            notifyItemRangeChanged(position, mDatas.size - position)
        }
    }
}